package com.luoxue.mito.util;

import java.io.*;
import java.net.URL;

public class FileUtil {
    /**
     * @param urlStr 图片链接地址，如：https://game.gtimg.cn/images/lol/act/img/rune/Predator.png
     * @param path   文件存放路径及名称，如：/springtest/item/2021-12-24/1640323863344/F00413-6.png
     *               链接url下载图片到服务器
     */
    public static void downloadFileToServer(String urlStr, String path) {
        URL url;
        try {
            url = new URL(urlStr);
            DataInputStream dataInputStream = new DataInputStream(url.openStream());
            File file = new File(path);
            if (!file.exists()) {
                file.getParentFile().mkdirs();
                try {
                    file.createNewFile();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            FileOutputStream fileOutputStream = new FileOutputStream(file);
            ByteArrayOutputStream output = new ByteArrayOutputStream();

            byte[] buffer = new byte[1024];
            int length;
            while ((length = dataInputStream.read(buffer)) > 0) {
                output.write(buffer, 0, length);
            }
            fileOutputStream.write(output.toByteArray());
            dataInputStream.close();
            fileOutputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
